package com.hd.trans.ui.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.binding.visible
import com.hd.trans.databinding.ActivityAiChatBinding
import com.hd.trans.db.bean.AIChatType
import com.hd.trans.db.bean.AiChatRecordDataMgr
import com.hd.trans.dialog.AiSettingDialog
import com.hd.trans.files.adapter.AIAnswerAdapter
import com.hd.trans.homefun.EventCode
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.network.bean.UserInfoBean
import com.hd.trans.network.bean.aiChat.AIAnswer
import com.hd.trans.network.bean.aiChat.AIDataType
import com.hd.trans.network.bean.aiChat.TaskStatus
import com.hd.trans.network.component.AiChatManager
import com.hd.trans.ui.base.LimitBaseActivity
import com.hd.trans.ui.model.AiChatViewModel
import com.hd.trans.utils.DateUtil
import com.hd.trans.utils.KeyEventUtil
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans

class AiChatActivity: LimitBaseActivity(){
    private lateinit var mAiChatViewModel: AiChatViewModel
    private lateinit var mAiChatManager: AiChatManager
    private var isCanOpt = true//是否可以提问，控制发送按钮（未返回结果不可再次提问）
    lateinit var mDataBinding: ActivityAiChatBinding
    override fun getLayoutId(): Int {
        return R.layout.activity_ai_chat
    }

    companion object {
        @JvmStatic
        var userInfo: UserInfoBean? = null
        @JvmStatic
        var questionType: Int = 0

        @JvmStatic
        fun open(context: Context, listener: LimitUseListener? = null, bean: UserInfoBean? = null, type: Int = 0) {
            limitListener = listener
            questionType = type
            userInfo = bean
            PreferenceMgr.getInstance().userInfo = bean
            val intent = Intent(context, AiChatActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val llBottomParams by lazy {
        mDataBinding.llBottom.layoutParams as RelativeLayout.LayoutParams
    }

    private val mAdapter by lazy {

        AIAnswerAdapter().apply {

            addAll(ArrayList<AIAnswer>().apply {
                add(
                    AIAnswer(
                        AIChatType.values()[questionType].itemTips,
                        AIDataType.COMM_TIPS,
                        AIChatType.values()[questionType].questionList,
                        AIChatType.values()[questionType].showIcon,
                    )
                )
                addAll(AiChatRecordDataMgr.getAllAIAnswerByScene(AIChatType.values()[questionType].scene))
            })

            //问题回调
            onQuestionClickListener = {
                if (isCanOpt) {
                    if(!intercept(EventCode.AI_TRANS)){
                        postTaskChat(it, true)
                    }
                }
            }
            //复制监听
            onAnswerCopyListener = {
                TranslationInterior.getTrackerListener().click(TrackerForTrans.AI_TRANS, "复制")
                if (it.isEmpty()) {
                    ToastUtils.showNormal(getString(R.string.tips_empty_content))
                } else {
                    val cmb = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                    val mClipData = ClipData.newPlainText("text", it)
                    cmb.setPrimaryClip(mClipData)
                    ToastUtils.showNormal(R.string.copy_success)
                }
            }
            //删除监听
            onAnswerDeleteListener = {position, answer ->
                TranslationInterior.getTrackerListener().click(TrackerForTrans.AI_TRANS, "删除")
                this.delete(position)
                AiChatRecordDataMgr.deleteAiChatRecordByCreateTime(answer.createTime)
            }
            //删除监听
            onAnswerDeleteAllListener = {
                TranslationInterior.getTrackerListener().click(TrackerForTrans.AI_TRANS, "清除全部记录")
                this.clear()
                AiChatRecordDataMgr.deleteAllAiChatRecord()
            }

        }
    }
    override val pageType: EventCode
        get() = EventCode.AI_TRANS

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        //视图埋点
        TranslationInterior.getTrackerListener().view(TrackerForTrans.AI_TRANS)
        mAiChatViewModel = ViewModelProvider(this).get(AiChatViewModel::class.java)
        mAiChatManager = AiChatManager()
        //activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        initView()
        initData()
    }

    private fun initView() {
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_ai_chat)
        mDataBinding.apply {
            click = this@AiChatActivity

            etInput.requestFocus()//获取焦点 光标出现
            /**
             * 监听软键盘弹起
             */
            KeyEventUtil(activity).apply {
                setListener(object : KeyEventUtil.OnSoftKeyBoardChangeListener {
                    override fun keyBoardShow(height: Int) {
                        llBottomParams.bottomMargin = height
                        llBottom.layoutParams = llBottomParams
                    }

                    override fun keyBoardHide(height: Int) {
                        llBottomParams.bottomMargin = 0
                        llBottom.layoutParams = llBottomParams
                    }

                })
            }

            etInput.apply {
                onFocusChangeListener =
                    View.OnFocusChangeListener { v, hasFocus ->
//                    showLayoutBottom()
                        Log.e(TAG, "hasFocus = $hasFocus")
                    }

                addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(
                        s: CharSequence?,
                        start: Int,
                        count: Int,
                        after: Int,
                    ) {}
                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                        if (s.isNullOrEmpty()) {
                            tvSend.isEnabled = false
                            tvSend.isSelected = true
                        } else {
                            tvSend.isEnabled = true && isCanOpt
                            tvSend.isSelected = false || !isCanOpt
                        }
                    }
                    override fun afterTextChanged(s: Editable?) {}
                })
                setText("")
            }

            recyclerView.apply {
                layoutManager = LinearLayoutManager(this@AiChatActivity)
                adapter = mAdapter
            }
            recyclerView.scrollToPosition(mAdapter.itemCount - 1)
            ivSetting.visible = TranslationInterior.isDebug()
            if(!TranslationInterior.isDebug()){
                PreferenceMgr.getInstance().aiPrefix = ""
                PreferenceMgr.getInstance().aiSuffix = ""
            }
        }
    }

    private fun initData() {
        mAiChatViewModel.mLiveResult.observe(this) {
            isCanOpt = true
            mAdapter.onUpdateAnswer(it)
            mXHandler.postDelayed({
                mDataBinding.recyclerView.smoothScrollToPosition(mAdapter.itemCount - 1)
            },300)
            AiChatRecordDataMgr.saveAIAnswer(it)//保存数据库
        }

        mAiChatViewModel.mLoading.observe(this) {
            mAdapter.onUpdateAnswer(AIAnswer(it))
        }

        updateEtInputHint(false)
    }

    private fun updateEtInputHint(deplete: Boolean) {
        if(DateUtil.getDateStr3(PreferenceMgr.getInstance().aiTransLimitDate)
            != DateUtil.getDateStr3(PreferenceMgr.getInstance().serverTimeStamp)){
            //新的一天
            PreferenceMgr.getInstance().aiTransLimitDate = PreferenceMgr.getInstance().serverTimeStamp
            PreferenceMgr.getInstance().aiTransRemainderLimitNumber = PreferenceMgr.getInstance().aiTransVipLimitNumber

        }
        if(PreferenceMgr.getInstance().aiTransRemainderLimitNumber > PreferenceMgr.getInstance().aiTransVipLimitNumber){
            PreferenceMgr.getInstance().aiTransRemainderLimitNumber = PreferenceMgr.getInstance().aiTransVipLimitNumber
        }
        if(deplete){
            PreferenceMgr.getInstance().aiTransRemainderLimitNumber -= 1
        }
        val remainder = PreferenceMgr.getInstance().aiTransRemainderLimitNumber
        val hint = if(remainder > 0){
            String.format(getString(R.string.trans_ai_limit_number), PreferenceMgr.getInstance().aiTransVipLimitNumber.toString(), remainder.toString())
        }else{
            getString(R.string.trans_no_limit_number)
        }
        mDataBinding.etInput.hint = hint
    }

    private fun postTaskChat(content: String, isFromQuestion: Boolean = false) {
        if(mDataBinding.etInput.hint == getString(R.string.trans_no_limit_number)){
            ToastUtils.showNormal(getString(R.string.trans_no_limit_number))

            mAdapter.add(
                AIAnswer(
                    "亲爱的用户，目前AI智能翻译功能正处于测试学习阶段，我们将收集学习模型进行功能优化。每天零点重新刷新开放。",
                    AIDataType.ANSWER,
                    placeholder = AIChatType.values()[questionType].showIcon,
                    status = TaskStatus.DONE
                )
            )
            mDataBinding.recyclerView.scrollToPosition(mAdapter.itemCount - 1)
            return
        }

        isCanOpt = false

        //历史对话
        val history = if(mAdapter.getData().isNotEmpty() && mAdapter.itemCount >= 2){
            arrayListOf<String>().apply {
                if(mAdapter.itemCount > 6){
                    //截取最后6条记录
                    mAdapter.getData().subList(mAdapter.itemCount - 6,mAdapter.itemCount - 1).forEach {
                        add(it.output)
                    }
                }else{
                    mAdapter.getData().forEach {
                        add(it.output)
                    }
                }
            }.also {
                if(it.size%2 != 0){
                    //确保是偶数
                    it.removeAt(0)
                }
            }
        }else{
            null
        }

        val question = AIAnswer(content, AIDataType.QUESTION, headUrl = userInfo?.headPortrait)
        mAdapter.add(question)
        //此处可以把记录保存到服务端。
        //存：https://gitlab.huduntech.com/php/img-convert/-/wikis/sub/ai-chat/histories/save
        //删：https://gitlab.huduntech.com/php/img-convert/-/wikis/sub/ai-chat/histories/delete
        //查：https://gitlab.huduntech.com/php/img-convert/-/wikis/sub/ai-chat/histories/list
        AiChatRecordDataMgr.saveAIAnswer(question)//保存到本地数据库

        mDataBinding.etInput.setText("")
        updateEtInputHint(true)

        mAdapter.add(
            AIAnswer(
                "小助手正在思考中...",
                AIDataType.ANSWER,
                placeholder = AIChatType.values()[questionType].showIcon
            )
        )
        mDataBinding.recyclerView.scrollToPosition(mAdapter.itemCount - 1)

        mAiChatViewModel.startCountDownTimer()
        //嵌入配置
        val embeddingResults = if(
            isFromQuestion ||
            (PreferenceMgr.getInstance().aiPrefix.isNullOrEmpty() && PreferenceMgr.getInstance().aiSuffix.isNullOrEmpty())
        ){
            content
        }else{
            "${PreferenceMgr.getInstance().aiPrefix}\"${content}\"${PreferenceMgr.getInstance().aiSuffix}"
        }
        //调试userInfo
        if(userInfo == null && TranslationInterior.isDebug()){
            userInfo = UserInfoBean(
                "AthqYb-EcVjWZUcFURS59LmUywg63GUvEYCRZXHQTNNXXu9K48p0rkHRoNoW8bMh2MpY0zl6N9vBFs1K0rv57hLRXA",
                "o0j5B5wYZWlE2CXl-REscbRLdYl0",
                "",
                ""
            )
        }
        mAiChatManager.chatSSE(embeddingResults, userInfo!!, history = history){
            mAiChatViewModel.stopCountDownTimer()
            val result = it.output.ifEmpty {
                it.message
            }

            mAiChatViewModel.mLiveResult.postValue(AIAnswer(result, AIDataType.ANSWER, status = TaskStatus.DONE))
        }
    }

    override fun onViewClick(v: View?) {
        when(v){
            mDataBinding.ivBack -> {
                finish()
            }
            mDataBinding.tvSend -> {
                TranslationInterior.getTrackerListener().click(TrackerForTrans.AI_TRANS, "发送")
                if(!intercept(EventCode.AI_TRANS)){
                    postTaskChat(mDataBinding.etInput.text.toString().trim())
                }
            }
            mDataBinding.ivSetting -> {
                AiSettingDialog().show(supportFragmentManager,"ai_setting_dialog")
            }
        }
    }


}